<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!-- 主表单字段 -->
      <el-form-item label="科室" prop="deptId">
        <el-input v-model="formData.deptName" placeholder="请输入仓库编号" disabled />
      </el-form-item>
      <el-form-item label="出库单号" prop="no">
        <el-input v-model="formData.no" placeholder="请输入出库单号" disabled />
      </el-form-item>
      <!-- <el-form-item label="核销报废类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择核销报废类型" disabled>
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.WRITEOFF_SCRAP_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="出库时间" prop="outTime">
        <el-date-picker
          v-model="formData.outTime"
          type="date"
          value-format="x"
          placeholder="选择出库时间"
          disabled
        />
      </el-form-item> -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" disabled />
      </el-form-item>
      <!-- <el-form-item label="合计数量" prop="totalCount">
        <el-input v-model="formData.totalCount" placeholder="请输入合计数量" disabled />
      </el-form-item> -->
      
      <!-- <el-form-item label="审核状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态" disabled>
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.WRITEOFF_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="图片" prop="fileUrl">
        <!-- <UploadImg v-model="formData.fileUrl" disabled /> -->
        <UploadImgs v-model="formData.fileUrl" disabled />
      </el-form-item>
      <!-- 加一个 -->
    </el-form>

    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="核销报废管理单项" name="checkOutItem">
        <CheckOutItemFormDetail 
          ref="checkOutItemFormRef" 
          :out-id="formData.id" 
          :disabled="isSubFormDisabled"
          :dept-id="formData.deptId"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- <el-form-item label="审核意见" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入审核意见" />
      </el-form-item> -->
    <!-- 审核通过和退回按钮 -->
    <!-- <div style="margin-top: 20px; text-align: right;">
      <el-button @click="handleApprove" type="success" :disabled="formLoading">审核通过</el-button>
      <el-button @click="handleReject" type="danger" :disabled="formLoading">退回</el-button>
    </div> -->
    <!-- 审核意见 -->
    <el-form-item label="审核意见" prop="comments" style="margin: 20px;">
        <el-input 
          v-model="formData.comments" 
          type="textarea" 
          placeholder="请输入详细的审核意见，包括通过或退回的原因。" 
          :rows="4" 
          maxlength="500" 
          show-word-limit
        />
      </el-form-item>

    <template #footer>
      <el-button @click="submitForm" type="success" :disabled="formLoading">审核通过</el-button>
      <el-button @click="handleReject" type="danger" :disabled="formLoading">退回</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getStrDictOptions, getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { CheckOutApi, CheckOutVO } from '@/api/erp/checkout'
import CheckOutItemFormDetail from './components/CheckOutItemFormDetail.vue'
import { SecStockApi, SecStockVO } from '@/api/erp/secstock'

/** ERP 核销报废管理单 表单 */
defineOptions({ name: 'CheckOutForm' })
// const props = defineProps(['taskId'])
const props = defineProps<{
  taskId: string // 流程任务ID
}>()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deptId: undefined,
  deptName: undefined,
  no: undefined,
  type: undefined,
  outTime: undefined,
  totalCount: undefined,
  remark: undefined,
  status: undefined,
  fileUrl: [] as string[], // 修改为数组
  createTime: undefined,
  taskId: undefined,  // 审批任务ID
  comments:undefined, // 审批意见
  outId: undefined, // 出库单ID
})
const formRules = reactive({
  deptId: [{ required: true, message: '仓库编号不能为空', trigger: 'blur' }],
  no: [{ required: true, message: '出库单号不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '核销报废类型不能为空', trigger: 'change' }],
  // outTime: [{ required: true, message: '出库时间不能为空', trigger: 'blur' }],
  // totalCount: [{ required: true, message: '合计数量不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('checkOutItem')
const checkOutItemFormRef = ref()
const isSubFormDisabled = ref(true) // 控制子表表单的禁用状态

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  // console.log("props.taskId",props)
  dialogVisible.value = true
  // dialogTitle.value = t('action.' + type)
  dialogTitle.value = "审批"
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CheckOutApi.getCheckOut(id)
      // console.log("formData.value",formData.value)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await checkOutItemFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'checkOutItem'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CheckOutVO
    // 拼接子表的数据
    data.checkOutItems = checkOutItemFormRef.value.getData()
    
    // console.log("子表的数据",checkOutItemFormRef.value.getData())
    // 修改状态为已审核
    data.status = 3
    data.taskId = props.taskId
    if (formType.value === 'create') {
      await CheckOutApi.createCheckOut(data)
      message.success(t('common.createSuccess'))
    } else {
      // 修改状态 并 减少子页面每个商品对应数量的库存
      await CheckOutApi.updateCheckOut(data)
      message.success("审核通过")
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 退回按钮点击事件
const handleReject = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await checkOutItemFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'checkOutItem'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CheckOutVO
    // 拼接子表的数据
    data.checkOutItems = checkOutItemFormRef.value.getData()
    // 修改状态为已退回
    data.status = 2
    data.taskId = props.taskId
    if (formType.value === 'create') {
      await CheckOutApi.createCheckOut(data)
      message.success(t('common.createSuccess'))
    } else {
      await CheckOutApi.updateCheckOut(data)
      message.success("退回成功")
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deptId: undefined,
    deptName: undefined,
    no: undefined,
    type: undefined,
    outTime: undefined,
    totalCount: undefined,
    remark: undefined,
    fileUrl: undefined,
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
/* 添加一些样式以优化表单项的间距 */
.el-form-item {
  margin-bottom: 24px;
}

/* 调整审核意见文本区域的样式 */
.el-textarea {
  width: 100%;
}
</style>